<?php
class ControllerAccountAddress extends AccountController {
	
  	public function index() {
  		M('account/address');
		$this->getList();
  	}

  	public function insert() {
  		M('account/address');
    	if ($this->request->isPost() && $this->validateForm()) {
			$this->model_account_address->addAddress($this->request->post);

      		$this->session->set_flashdata('success', $this->_['text_insert']);
	  		$this->redirect(US('account/address'));
    	}

		$this->getForm();
  	}

  	public function update() {
  		M('account/address');
    	if ($this->request->isPost() && $this->validateForm()) {
       		$this->model_account_address->editAddress($this->request->get['address_id'], $this->request->post);

			// Default Shipping Address
			if (isset($this->session->data['shipping_address_id'])
					&& ($this->request->get['address_id'] == $this->session->data['shipping_address_id'])) {
				$this->session->data['shipping_country_id'] = $this->request->post['country_id'];
				$this->session->data['shipping_zone_id'] = $this->request->post['zone_id'];
				$this->session->data['shipping_postcode'] = $this->request->post['postcode'];

				unset($this->session->data['shipping_method']);
				unset($this->session->data['shipping_methods']);
			}

			// Default Payment Address
			if (isset($this->session->data['payment_address_id'])
					&& ($this->request->get['address_id'] == $this->session->data['payment_address_id'])) {
				$this->session->data['payment_country_id'] = $this->request->post['country_id'];
				$this->session->data['payment_zone_id'] = $this->request->post['zone_id'];

				unset($this->session->data['payment_method']);
				unset($this->session->data['payment_methods']);
			}

			$this->session->set_flashdata('success', $this->_['text_update']);
	  		$this->redirect(US('account/address'));
    	}

		$this->getForm();
  	}

  	public function delete() {
  		M('account/address');
    	if (isset($this->request->get['address_id']) && $this->validateDelete()) {
			$this->model_account_address->deleteAddress($this->request->get['address_id']);

			// Default Shipping Address
			if (isset($this->session->data['shipping_address_id'])
					&& ($this->request->get['address_id'] == $this->session->data['shipping_address_id'])) {
				unset($this->session->data['shipping_address_id']);
				unset($this->session->data['shipping_country_id']);
				unset($this->session->data['shipping_zone_id']);
				unset($this->session->data['shipping_postcode']);
				unset($this->session->data['shipping_method']);
				unset($this->session->data['shipping_methods']);
			}

			// Default Payment Address
			if (isset($this->session->data['payment_address_id'])
					&& ($this->request->get['address_id'] == $this->session->data['payment_address_id'])) {
				unset($this->session->data['payment_address_id']);
				unset($this->session->data['payment_country_id']);
				unset($this->session->data['payment_zone_id']);
				unset($this->session->data['payment_method']);
				unset($this->session->data['payment_methods']);
			}

			$this->session->set_flashdata('success', $this->_['text_delete']);
	  		$this->redirect(US('account/address'));
    	}

		$this->getList();
  	}

  	protected function getList() {

      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->_['heading_title'],
			'href'      => US('account/address'),
        	'separator' => $this->_['text_separator']
      	);

		$this->data['success'] = $this->session->flashdata('success');

    	$this->data['addresses'] = array();

		$results = $this->model_account_address->getAddresses();

    	foreach ($results as $result) {
			if ($result['address_format']) {
      			$format = $result['address_format'];
    		} else {
				$format = '{firstname} {lastname}' . "\n" . '{company}' . "\n" . '{address_1}' . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}';
			}

    		$find = array(
	  			'{firstname}',
	  			'{lastname}',
	  			'{company}',
      			'{address_1}',
      			'{address_2}',
     			'{city}',
      			'{postcode}',
      			'{zone}',
				'{zone_code}',
      			'{country}'
			);

			$replace = array(
	  			'firstname' => $result['firstname'],
	  			'lastname'  => $result['lastname'],
	  			'company'   => $result['company'],
      			'address_1' => $result['address_1'],
      			'address_2' => $result['address_2'],
      			'city'      => $result['city'],
      			'postcode'  => $result['postcode'],
      			'zone'      => $result['zone'],
				'zone_code' => $result['zone_code'],
      			'country'   => $result['country']
			);

      		$this->data['addresses'][] = array(
        		'address_id' => $result['address_id'],
        		'address'    => str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format)))),
        		'update'     => U('account/address/update', 'address_id=' . $result['address_id'], 'SSL'),
				'delete'     => U('account/address/delete', 'address_id=' . $result['address_id'], 'SSL')
      		);
    	}

		$this->display('account/address_list.tpl');
  	}

  	protected function getForm() {

      	$this->data['breadcrumbs'][] = array(
        	'text'      => $this->_['heading_title'],
			'href'      => US('account/address'),
        	'separator' => $this->_['text_separator']
      	);

		if (!isset($this->request->get['address_id'])) {
      		$this->data['breadcrumbs'][] = array(
        		'text'      => $this->_['text_edit_address'],
				'href'      => US('account/address/insert'),
        		'separator' => $this->_['text_separator']
      		);
		} else {
      		$this->data['breadcrumbs'][] = array(
        		'text'      => $this->_['text_edit_address'],
				'href'      => US('account/address/update', 'address_id=' . $this->request->get['address_id']),
        		'separator' => $this->_['text_separator']
      		);
		}
		
		$this->document->addScript('static/javascript/jquery/jquery.validate.js');
		
		$address_id = (int) G('address_id', 0);
		
		if ($address_id) {
    		$this->data['action'] = U('account/address/update', 'address_id=' . $address_id, 'SSL');
    		if (!$this->request->isPost()) {
    			$this->vo->data = $this->model_account_address->getAddress($address_id);
    		}
		} else {
    		$this->data['action'] = U('account/address/insert', '', 'SSL');
		}

		M('account/customer_group', 'customer_group');
		$customer_group_info = $this->customer_group->getCustomerGroup($this->customer->getCustomerGroupId());

		if ($customer_group_info) {
			$this->data['company_id_display'] = $customer_group_info['company_id_display'];
			$this->data['tax_id_display'] = $customer_group_info['tax_id_display'];
		} else {
			$this->data['company_id_display'] = '';
			$this->data['tax_id_display'] = '';
		}

		//default ?
    	if (isset($this->request->post['default'])) {
      		$this->data['default'] = $this->request->post['default'];
    	} elseif ($address_id) {
      		$this->data['default'] = $this->customer->getAddressId() == $address_id;
    	} else {
			$this->data['default'] = false;
		}

    	$this->data['countries'] = cache_read('country.php');
    	
		$this->display('account/address_form.tpl');
  	}

  	protected function validateForm() {
		$this->load->library('form_validation', true);
		
		$this->form_validation->set_rules('firstname', '', 'required|range_length[1,32]', $this->_['error_firstname']);
		$this->form_validation->set_rules('lastname', '', 'required|range_length[1,32]', $this->_['error_lastname']);
		$this->form_validation->set_rules('address_1', '', 'required|range_length[3,128]', $this->_['error_address_1']);
		$this->form_validation->set_rules('city', '', 'required|range_length[2,128]', $this->_['error_city']);

		M('localisation/country', 'country');

		$country_info = $this->country->getCountry($this->request->post['country_id']);
		if ($country_info) {
			if ($country_info['postcode_required']) {
				$this->form_validation->set_rules('postcode', '', 'required|range_length[2,10]', $this->_['error_postcode']);
			}

			// VAT Validation
			$this->load->helper('vat');

			if (C('config_vat') && !empty($this->request->post['tax_id']) && (vat_validation($country_info['iso_code_2'], $this->request->post['tax_id']) == 'invalid')) {
				$this->form_validation->set_rules('tax_id', '', 'required');
				$this->form_validation->set_error('tax_id', $this->_['error_vat']);
			}
		}

    	$this->form_validation->set_rules('country_id', '', 'required', $this->_['error_country']);
		$this->form_validation->set_rules('zone_id', '', 'required', $this->_['error_zone']);

    	return $this->form_validation->run();
  	}

  	protected function validateDelete() {
    	if ($this->model_account_address->getTotalAddresses() == 1) {
      		$this->setMessage('error_warning', $this->_['error_delete']);
			return false;
    	}

    	if ($this->customer->getAddressId() == $this->request->get['address_id']) {
      		$this->setMessage('error_warning', $this->_['error_default']);
			return false;
    	}
		
		return true;
  	}
}
?>